package com.wolfalpha.utron.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;

import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.EMLog;
import com.wolfalpha.utron.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import easemob.chatuidemo.Constant;

/**
 * 文字处理的类
 *
 * @author
 */
public class StringUtils {
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * String to JSON
     *
     * @param json
     * @return
     * @throws JSONException
     */
    public static JSONObject toJSONObject(String json) throws JSONException {
        if (!isEmpty(json)) {
            if (json.indexOf("[") == 0) {
                json = json.substring(1, json.length());
            }
            if (json.lastIndexOf("]") == json.length()) {
                json = json.substring(0, json.length() - 1);
            }
            return new JSONObject(json);
        }
        return null;
    }

    /**
     * String to JSONArray
     *
     * @param json
     * @return
     * @throws JSONException
     */
    public static JSONArray toJSONArray(String json) throws JSONException {
        if (!isEmpty(json)) {
            // if (json.indexOf("[") == 0) {
            // json = json.substring(1, json.length());
            // }
            // if (json.lastIndexOf("]") == json.length()) {
            // json = json.substring(0, json.length() - 1);
            // }
        }
        return new JSONArray(json);
    }

    /**
     * String to date
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * TimeStamp to Date
     *
     * @param timestampString 毫秒
     * @return
     */
    public static String TimeStamp2Date(long timestampString) {
        Long timestamp = timestampString;
        return dateFormater.get().format(new Date(timestamp));
    }

    /**
     * TimeStamp to Date
     *
     * @param timestampString 毫秒
     * @return
     */
    public static String TimeStamp2Date2(long timestampString) {
        Long timestamp = timestampString;
        return dateFormater2.get().format(new Date(timestamp));
    }

    /**
     * @param sdate
     * @return
     */
    public static String friendly_Distance(double distance) {
        String dis = "";
        if (distance >= 1000) {
            if (distance / 1000 >= 1000) {
                dis = ">1000km";
            } else if (distance / 1000 >= 100) {
                dis = ">100km";
            } else {
                dis = String.format("%.1f", (distance / 1000)) + "km";
            }
        } else {
            dis = distance + "m";
        }
        return dis;
    }

    /**
     * 格式化时间
     *
     * @param m
     * @return
     */
    public static String friendly_time(long m) {
        long delay = System.currentTimeMillis()/1000 - m;
//        System.out.println(delay);
        if (delay < 3) {
            //3秒内
            return "刚刚";
        }
        if (delay < 60) {
            return delay + "秒前";
        }
        if (delay < 3600) {
            return delay / 60 + "分钟前";
        }
        if (delay < 3600 * 24) {
            return delay / 3600 + "小时前";
        }
        if (delay < 7 * 3600 * 24) {
            return delay / 3600 * 24 + "天前";
        }

        String date = TimeStamp2Date(m);
        return date;
    }

    public static String friendly_time(String olddate) {
        Date time = toDate(olddate);
        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0) {
                long min = (cal.getTimeInMillis() - time.getTime()) / 60000;
                if (min == 0) {
                    ftime = Math.max(
                            (cal.getTimeInMillis() - time.getTime()) / 1000, 1)
                            + "秒";// second
                } else {
                    ftime = Math.max(
                            (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                            + "分钟";// minute
                }
            } else
                ftime = hour + "小时";// hour
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟";
            else
                ftime = hour + "小时";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    /**
     * 判断是否是今天
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断是否是空值
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否是邮箱地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 强制转换成int
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 强制转换成int
     *
     * @param obj
     * @return Object
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 强制转换成Long
     *
     * @param obj
     * @return String
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 强制转换成 Boolean
     *
     * @param b
     * @return 默认false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }


    /**
     * 获取方向
     *
     * @param context
     * @return
     */
    public static List<String> getDirsValues(Context context) {
        Map<Integer, String> dirs = new HashMap<Integer, String>();
        String[] nameArr = context.getResources().getStringArray(R.array.dirs_name);
        return Arrays.asList(nameArr);
    }
//
//    /**
//     * 通过名字查找ID
//     *
//     * @param name
//     * @return
//     */
//    public static int getIdByNameDirs(String name) {
//        for (int key : AppContext.getInstance().getDirs().keySet()) {
//            if (AppContext.getInstance().getDirs().get(key).equals(name)) {
//                return key;
//            }
//        }
//        return 0;
//    }


    /**
     * 根据消息内容和消息类型获取消息内容提示
     *
     * @param message
     * @param context
     * @return
     */
    public static String getMessageDigest(EMMessage message, Context context) {
        String digest = "";
        switch (message.getType()) {
            case LOCATION: // 位置消息
                if (message.direct == EMMessage.Direct.RECEIVE) {
                    //从sdk中提到了ui中，使用更简单不犯错的获取string方法
//              digest = EasyUtils.getAppResourceString(context, "location_recv");
                    digest = context.getResources().getString(R.string.location_recv);
                    digest = String.format(digest, message.getFrom());
                    return digest;
                } else {
//              digest = EasyUtils.getAppResourceString(context, "location_prefix");
                    digest = context.getResources().getString(R.string.location_prefix);
                }
                break;
            case IMAGE: // 图片消息
                digest = context.getResources().getString(R.string.picture);
                break;
            case VOICE:// 语音消息
                digest = context.getResources().getString(R.string.voice);
                break;
            case VIDEO: // 视频消息
                digest = context.getResources().getString(R.string.video);
                break;
            case TXT: // 文本消息
                if (!message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
                    TextMessageBody txtBody = (TextMessageBody) message.getBody();
                    digest = txtBody.getMessage();
                } else {
                    TextMessageBody txtBody = (TextMessageBody) message.getBody();
                    digest = context.getResources().getString(R.string.voice_call) + txtBody.getMessage();
                }
                break;
            case FILE: //普通文件消息
                digest = context.getResources().getString(R.string.file);
                break;
            default:
                EMLog.e("HXMessage", "error, unknow type");
                return "";
        }

        return digest;
    }

    /**
     * 获取应用名
     *
     * @param context
     * @param pID
     * @return
     */
    public static String getAppName(Context context, int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = context.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }


    /**
     * MD5 加密
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        byte[] buf = str.getBytes();
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(buf);
            byte[] tmp = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : tmp) {
                sb.append(Integer.toHexString(b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return str;
    }
}